package client;

import com.shcm.bean.BalanceResultBean;
import com.shcm.bean.SendResultBean;
import com.shcm.send.DataApi;
import com.shcm.send.OpenApi;
import common.consts.Consts;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by aceyin on 15/6/23.
 */
@Component
public class SmsClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsClient.class);

    private static String sOpenUrl = "http://smsapi.c123.cn/OpenPlatform/OpenApi";
    private static String sDataUrl = "http://smsapi.c123.cn/DataPlatform/DataApi";

    private static final String account = "1001@501150220001";

    // 接口密钥
    private static final String authkey = "96E50C6948BAA6E8279086877D5C94E1";

    // 通道组编号
    private static final int cgid = 4662;

    // 默认使用的签名编号(未指定签名编号时传此值到服务器)
    private static final int csid = 4903;

    @PostConstruct
    public void setup() {
        // 发送参数
        OpenApi.initialzeAccount(sOpenUrl, account, authkey, cgid, csid);
        // 状态及回复参数
        DataApi.initialzeAccount(sDataUrl, account, authkey);
        // 取帐户余额
        BalanceResultBean br = OpenApi.getBalance();

        if (br == null) {
            LOGGER.error("短信验证码余额获取接口发生异常！");
        } else {
            LOGGER.info("初始化短信接口成功");
        }

        int remain = br.getRemain();
        if (br.getResult() < 1) {
            LOGGER.error("获取可用余额失败: " + br.getErrMsg());
        } else {
            LOGGER.info("短信接口可用余额:{}条", remain);
        }
        if (remain < Consts.SMS_BALANCE_WARNING_THRESHOLD) {
            LOGGER.warn("警告:短信验证码可用余额不足1000条,可用条数:{}", remain);
            send(Consts.SYSTEM_ADMIN_MOBILES, Consts.SMS_BALANCE_WARNING);
        }
    }

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @param content
     * @return
     */
    public boolean send(String mobile, String content) {
        String testEnv = System.getProperty(Consts.KEY_IS_TEST_ENV);
        if (StringUtils.isNotBlank(testEnv)) {
            return true;
        }

        List<SendResultBean> listItem = OpenApi.sendOnce(mobile, content, cgid, csid, null);
        if (listItem == null || listItem.size() == 0) {
            return false;
        }
        SendResultBean resultBean = listItem.get(0);
        int result = resultBean.getResult();

        if (result < 1) {
            return false;
        }

//        long msgId = resultBean.getMsgId();
        return true;
    }
}
